import {createRouter, createWebHashHistory, RouterView, createWebHistory} from 'vue-router'
import {MenuTypeEnum} from "@/enums/appEnum";
import {constantRoutes, LAYOUT} from "./routes"
import {isExternal} from "@/utils/validate";

const modules = import.meta.glob('/src/views/**/*.vue')

// 过滤路由所需要的数据
export function filterRoutes(routes, firstRoute = true) {
    return routes.map((route) => {
        const routeRecord = createRouteRecord(route, firstRoute)
        if (route.children != null && route.children && route.children.length) {
            let children = filterRoutes(route.children, false)
            children = children.filter((item) => item !== '')
            routeRecord.children = children
        }
        return routeRecord
    })
}

export function createRouteRecord(route, firstRoute) {
    const routeRecord = {
        path: route.paths,
        name: Symbol(route.paths),
        meta: {
            title: route.name,
            query: route.params,
            icon: route.icon,
            hidden: route.is_show === 0,
            keepAlive: false,
            perms: route.perms,
            type: route.type,
            activeMenu: ''
        },
    }

    switch (route.type) {
        case MenuTypeEnum.DIRECTORY:
            routeRecord.component = firstRoute ? LAYOUT : RouterView;
            if (!route.children) {
                routeRecord.component = RouterView
            }
            break;
        case MenuTypeEnum.MENU:
            routeRecord.component = loadRouteView(route.component);
            break;
    }

    return routeRecord;
}

// 动态加载组件
export function loadRouteView(component) {
    try {
        component = '/views/' + component
        const key = Object.keys(modules).find((key) => {
            return key.includes(`${component}.vue`)
        })
        if (key) {
            return modules[key]
        }
        throw Error(`找不到组件${component}，请确保组件路径正确`)
    } catch (error) {
        console.error(error)
        return RouterView
    }
}

// 找有效的路由
export function findFirstValidRoute(routes) {
    for (const route of routes) {
        if (route.meta?.type === MenuTypeEnum.MENU && !route.meta?.hidden && !isExternal(route.path)) {
            return route.path
        }
        if (route.children) {
            const path = findFirstValidRoute(route.children)
            if (path) {
                return path
            }
        }
    }
}

const router = createRouter({
    // history: createWebHistory(import.meta.env.BASE_URL),
    history: createWebHashHistory(),
    routes: constantRoutes
})

export default router
